<template>
  <AcceptHandleHeadComponent
    ref="acceptHandleHeadRef"
    :ucolumns="ucolumns"
    :needDealNum="needDealNum"
    :type="LableTitle.condeployTodo"
    :needMoreQuery="true"
    :showCaseNoQuery="false"
    @myEvent="myEvent"
    @setColumns="setColumns"
    @onSearch="onSearch"
    @onReset="reQuery"
  >
    <div slot="headLeft">
      <a-form-item style="display: flex; margin-bottom: 0px">
        <a-input v-model="queryParam.f_name" placeholder="请输入申请人" allowClear style="height: 40px" />
      </a-form-item>
    </div>
    <!-- 其他查询条件 -->
    <div slot="more">
      <a-form layout="inline" class="accept_more_operate_moreForm">
        <a-collapse v-model="collapseKey" class="accept_more_operate_moreForm_collapse">
          <a-collapse-panel :show-arrow="false" disabled key="1" style="font-weight: bold">
            <div slot="header" class="accept_more_operate_moreForm_collapse_head">
              <a-row :gutter="48" style="width: 100%">
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="罪名：">
                    <a-input v-model="queryParam.f_crime" placeholder="请输入罪名" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="执行地">
                    <a-input v-model="queryParam.f_exeaddr" placeholder="请输入执行地" allowClear />
                  </a-form-item>
                </a-col>
                <a-col @click.stop="() => {}" :md="8" :sm="24">
                  <a-form-item label="布控编号">
                    <a-input v-model="queryParam.f_concode" placeholder="请输入布控编号" allowClear />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
            <a-row :gutter="48" style="width: 100%" class="accept_more_operate_moreForm_collapse_body">
              <a-col @click.stop="() => {}" :md="12" :sm="24">
                <a-form-item label="矫正开始时间：">
                  <a-date-picker
                    v-model="queryParam.f_startdate"
                    :style="{ width: 'calc(50% - 10px)' }"
                    placeholder="开始日期"
                    format="YYYY-MM-DD"
                    allowClear
                    @change="startdateListen()"
                  />
                  ~
                  <a-date-picker
                    v-model="queryParam.f_startdate_01"
                    :style="{ width: 'calc(50% - 12px)' }"
                    placeholder="结束日期"
                    format="YYYY-MM-DD"
                    allowClear
                    @change="startdateListen()"
                  />
                </a-form-item>
              </a-col>
              <a-col @click.stop="() => {}" :md="12" :sm="24">
                <a-form-item label="布控开始时间：">
                  <a-date-picker
                    v-model="queryParam.f_condate"
                    :style="{ width: 'calc(50% - 10px)' }"
                    placeholder="开始日期"
                    format="YYYY-MM-DD"
                    allowClear
                    @change="constartdateListen()"
                  />
                  ~
                  <a-date-picker
                    v-model="queryParam.f_condate_01"
                    :style="{ width: 'calc(50% - 12px)' }"
                    placeholder="结束日期"
                    format="YYYY-MM-DD"
                    allowClear
                    @change="constartdateListen()"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form>
    </div>

    <template slot="content">
      <div class="accept_content_table">
        <!-- 表格数据 -->
        <a-table
          :scroll="scroll"
          :columns="ucolumns"
          :data-source="listData"
          :pagination="upagination"
          :loading="loading"
          rowKey="taskid"
          @change="tableChange"
          size="middle"
          :bordered="ubordered"
          :rowClassName="rowClassName"
          :components="header"
          ref="table"
          :key="tableCountKey"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
          </span>

          <div slot="nameSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ record.name }}</span>
              </template>
              <a @click="showPersonInfo(record)">{{ record.name }}</a>
            </a-tooltip>
          </div>

          <div slot="crimeSlot" slot-scope="crime" class="beyond_hiding" style="width: 100%; text-align: left">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ crime }}</span>
              </template>
              {{ crime }}
            </a-tooltip>
          </div>

          <div slot="exeaddrSlot" slot-scope="exeaddr" class="beyond_hiding" style="width: 100%; text-align: left">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ exeaddr }}</span>
              </template>
              {{ exeaddr }}
            </a-tooltip>
          </div>

          <div slot="crctypeSlot" slot-scope="crctype" class="beyond_hiding" style="width: 100%">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ crcTypeLabel(crctype) }}</span>
              </template>
              {{ crcTypeLabel(crctype) }}
            </a-tooltip>
          </div>

          <div slot="startdateSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <span v-if="record.startdate"
              >{{ record.startdate | getTimeFormat('YYYY年M月D日') }} -
              {{ record.enddate | getTimeFormat('YYYY年M月D日') }}</span
            >
          </div>

          <div slot="constartdateSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
            <span v-if="record.constartdate"
              >{{ record.constartdate | getTimeFormat('YYYY年M月D日') }} -
              {{ record.conenddate | getTimeFormat('YYYY年M月D日') }}</span
            >
          </div>

          <div slot="operation" slot-scope="text, record" style="text-align: left">
            <a v-if="record.taskid" @click="showHand(record, '3')">处理</a>
            <a-divider v-if="record.taskid" type="vertical" />
            <a href="javascript:;" @click="viewHand(record, '4')">详情</a>
          </div>
        </a-table>
      </div>
      <CrcPersonModal ref="crcPersonModalRef"></CrcPersonModal>
    </template>
  </AcceptHandleHeadComponent>
</template>

<script>
import drag from '@/components/TableDrag/drag'
import { LableTitle } from '@/enumeration/LableTitle.js'
import { St_apply } from '@/enumeration/St_apply.js'
import { findList } from '@/api/correction/apl_condeploy_person.js'
import { queryMf_MyTaskUndoList } from '@/api/workflow/mf_MyTaskUndo.js'
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import AcceptHandleHeadComponent from '@/views/accept/component/AcceptHandleHeadComponent.vue'
import { getViewTaskByInstid } from '@/api/worktasks/wt_personal.js'
import { Tp_biztype } from '@/enumeration/Tp_biztype'
import { Tp_crc_user } from '@/enumeration/correction/Tp_crc_user'
import { Decrypt } from '@/enumeration/SM.js'
const ucolumns = [
  {
    title: '序号',
    width: 50,
    key: 'index',
    align: 'center',
    fixed: 'left',
    scopedSlots: { customRender: 'serial' },
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'nameSlot' },
  },
  {
    title: '布控编号',
    dataIndex: 'concode',
    key: 'concode',
    width: 200,
    align: 'center',
  },
  {
    title: '罪名',
    dataIndex: 'crime',
    key: 'crime',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'crimeSlot' },
  },
  {
    title: '矫正类型',
    dataIndex: 'crctype',
    key: 'crctype',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'crctypeSlot' },
  },
  {
    title: '矫正时间',
    dataIndex: 'startdate',
    key: 'startdate',
    width: 300,
    align: 'center',
    scopedSlots: { customRender: 'startdateSlot' },
  },
  {
    title: '布控时间',
    dataIndex: 'constartdate',
    key: 'constartdate',
    width: 300,
    align: 'center',
    scopedSlots: { customRender: 'constartdateSlot' },
  },
  {
    title: '执行地',
    dataIndex: 'exeaddr',
    key: 'exeaddr',
    width: 200,
    align: 'center',
    scopedSlots: { customRender: 'exeaddrSlot' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' },
  },
]

export default {
  data() {
    return {
      applyid: null,
      ucolumns: ucolumns,
      cardColumns: ucolumns,
      needDealNum: undefined,
      Tp_biztype: Tp_biztype,
      Tp_crc_user: Tp_crc_user,
      queryParam: {
        f_name: '', // 社矫对象
        f_crime: '', // 罪名
        f_exeaddr: '', // 执行地
        f_concode: '', // 布控编号
        f_startdate: null, // 矫正开始时间
        f_startdate_01: null, // 矫正结束时间
        f_condate: null, // 布控开始时间
        f_condate_01: null, // 布控结束时间
        f_status: null, // 主表状态
        f_reguserid: null,
        userid: '', // 用户id
        matid: null,
        pageNumber: 1,
        pageSize: 20,
      },
      listData: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共计 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      mixins: [drag],
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      LableTitle: LableTitle,
      currentTab: 'table',
      header: undefined,
      tableCountKey: 0,
      collapseKey: [], // 折叠面板key
      scroll: { x: 1000, y: 410 },
    }
  },
  components: {
    BusineUserTree: () => import('@/views/accept/BusineUserTree.vue'),
    CrcPersonModal: () => import('@/views/correction/condeploy/CrcPersonModal.vue'),
    AcceptHandleHeadComponent,
  },
  created() {
    try {
      //routeParam = JSON.parse(JSON.stringify(this.$route.query.queryParam))
      this.queryParam = { ...this.queryParam, ...this.$route.query.queryParam.TempqueryParam }
    } catch {
      console.log('路由传参非json格式')
    }
    this.headerChange()
    // 待处理人员
    this.initDefaultParam()
    this.queryList()
  },
  watch: {
    ucolumns: {
      handler(newValue, oldVal) {
        this.headerChange()
      },
      deep: true, // 深度监听
    },
  },
  methods: {
    myEvent(e) {
      if (e) {
        this.scroll.y = this.scroll.y + e
      } else {
        this.scroll.y = 410
      }
    },
    headerChange() {
      console.log('移动后', this.ucolumns)
      this.header = {
        header: {
          cell: drag.methods.initDrag(this.ucolumns),
        },
      }
    },
    setColumns(columns) {
      console.log('重置前', this.ucolumns)
      // tableCountKey自增是为了让表格控件每次销毁强制更新
      this.tableCountKey += 1
      this.ucolumns = columns
      // this.ucolumns = columns
      console.log('重置后', this.ucolumns)
      this.setCardColumns()
    },
    /**
     * 显示处理界面
     */
    showHand(record, pattern) {
      // 没有taskid不操作
      if (!record.taskid) {
        return
      }
      record.TempqueryParam = this.queryParam
      this.$router.push({
        path: `/CorrectionCondeployTodoOperation/${record.taskid}/${pattern}`,
        query: {
          url: '/CondeployTodo',
          queryParam: record,
        },
      })
    },
    /**
     * 详情
     */
    async viewHand(record, pattern) {
      console.log('record', record)
      const res = await getViewTaskByInstid(record.instid)
      console.log('taskid', res.data)
      record.TempqueryParam = this.queryParam
      if (res.data) {
        this.$router.push({
          path: `/CorrectionCondeployTodoOperation/${res.data}/${pattern}`,
          query: {
            url: '/CondeployTodo',
            queryParam: record,
          },
        })
      } else {
        this.$message.error('查询流程taskid失败')
      }
    },
    onSearch(val) {
      this.queryParam.pageNumber = 1
      this.queryParam.pageSize = 20
      this.queryList()
    },
    // 接收时间监听判断开始结束日期是否合理
    startdateListen() {
      if (
        this.queryParam.f_startdate > this.queryParam.f_startdate_01 &&
        this.queryParam.f_startdate &&
        this.queryParam.f_startdate_01
      ) {
        this.queryParam.f_startdate = undefined
      }
    },
    constartdateListen() {
      if (
        this.queryParam.f_condate > this.queryParam.f_condate_01 &&
        this.queryParam.f_condate &&
        this.queryParam.f_condate_01
      ) {
        this.queryParam.f_condate = undefined
      }
    },
    /**
     * 初始化设置默认值
     */
    initDefaultParam() {
      this.queryParam.f_status = [St_apply[6000601].value]
      this.queryParam.f_reguserid = this.currentUser.userId
      this.queryParam.userid = this.currentUser.userId
      this.queryParam.bizenum = this.Tp_biztype['correct'].value
      this.queryParam.matid = '100000_360100-000201000000-CRC-001-01'
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery() {
      this.queryParam = {
        f_name: '', // 社矫对象
        f_crime: '', // 罪名
        f_exeaddr: '', // 执行地
        f_concode: '', // 布控编号
        f_startdate: null, // 矫正开始时间
        f_startdate_01: null, // 矫正结束时间
        f_condate: null, // 布控开始时间
        f_condate_01: null, // 布控结束时间
        f_reguserid: null,
        userid: '', // 用户id
        f_status: [St_apply[6000601].value], // 主表状态
        matid: null,
        pageNumber: 1,
        pageSize: 20,
      }
      this.initDefaultParam()
      this.queryList()
    },
    tableChange(upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },
    tableChangeOther(upagination) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },
    getCpQueryParam() {
      // 时间转换
      const cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.f_startdate?.format) {
        cpQueryParam.f_startdate = this.queryParam.f_startdate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_startdate_01?.format) {
        cpQueryParam.f_startdate_01 = this.queryParam.f_startdate_01.format('YYYY-MM-DD') + ' 23:59:59'
      }
      if (this.queryParam.f_condate?.format) {
        cpQueryParam.f_condate = this.queryParam.f_condate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.f_condate_01?.format) {
        cpQueryParam.f_condate_01 = this.queryParam.f_condate_01.format('YYYY-MM-DD') + ' 23:59:59'
      }
      return cpQueryParam
    },
    async queryList() {
      const queryParam = this.getCpQueryParam()
      this.loading = true
      const { data } = await findList(queryParam).finally(() => {
        this.loading = false
      })
      this.listData = data.records || []
      this.listData.forEach((item) => {
        item.name = Decrypt(item.name)
        item.phone = Decrypt(item.phone)
        item.cardno = Decrypt(item.cardno)
      })
      this.upagination.total = data.total
      this.upagination.current = data.current
      this.upagination.pageSize = data.size
      this.needDealNum = data.total

      // 查找我能处理的流程任务, 添加taskid到列表数据
      const res = await queryMf_MyTaskUndoList({ userid: this.currentUser.userId }, { pageSize: 99999, state: '1' })
      if (res.code == 0 && res.data?.records) {
        // console.log('我能处理的流程任务', res)
        const tempMap = {}
        res.data.records.forEach((v) => {
          tempMap[v.processinstanceid] = v.taskid
        })
        this.listData.forEach((v, i) => {
          if (v.instid in tempMap) {
            this.$set(this.listData[i], 'taskid', tempMap[v.instid])
          }
        })
        // console.log('添加完成', this.listData)
      }
    },
    rowClassName(record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },
    setCardColumns() {
      const columns = this.ucolumns.filter((child) => child.key != 'index' && child.key != 'action')
      this.cardColumns = JSON.parse(JSON.stringify(columns))
    },
    crcTypeLabel(crcType) {
      if (this.Tp_crc_user[Number(crcType)]) {
        return this.Tp_crc_user[Number(crcType)].name
      }
      return ''
    },
    showPersonInfo(record) {
      this.$refs.crcPersonModalRef.init(record.perid)
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';
</style>

<style lang="scss" scoped>
@import '~@/assets/css/apply/breathingLamp.scss';
.cursor_pointer:hover {
  color: #55a7f5;
}
.accept_content {
  &_table {
    &_font_red {
      color: #ca0000;
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 400;
    }

    ::v-deep .ant-table-row-cell-break-word {
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 400;
      color: #2c2c2c;
    }

    ::v-deep .ant-table-thead > tr > th {
      height: 50px;
    }

    ::v-deep .ant-table-row-cell-break-word {
      font-size: 16px;
      font-family: 'PingFang-SC-Heavy';
      font-weight: 600;
      color: #2c2c2c;
    }

    // ::v-deep .ant-pagination-total-text {
    //   font-size: 16px;
    //   font-family: 'PingFang-SC-Heavy';
    //   font-weight: 400;
    //   color: #8e97b9;
    // }

    ::v-deep .ant-table-body,
    .ant-table-header {
      word-break: break-all;
      &::-webkit-scrollbar {
        width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
        // height: 10px;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #a2c6e1;
      }
      &::-webkit-scrollbar-track {
        // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 5px;
        background: transparent;
      }
    }
  }
}
</style>
